<template>
  <div class="store-analytics-container">
    <el-tabs v-model="activeTab" class="analytics-tabs">
      <el-tab-pane label="每日销售额" name="sales">
        <div class="chart-container">
          <div id="salesChart" class="chart" style="height: 600px; width: 100%;"></div>
        </div>
        <el-table :data="dailySales" class="analytics-table" style="width: 100%">
          <el-table-column prop="date" label="日期" />
          <el-table-column prop="total_amount" label="销售额" />
        </el-table>
        <el-pagination
            v-model:currentPage="currentPageSales"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="dailySales.length"
            @current-change="handleSalesPageChange"
        />
      </el-tab-pane>
      <el-tab-pane label="每月销售额" name="monthly-sales">
        <div class="chart-container">
          <div id="monthlySalesChart" class="chart" style="height: 600px; width: 100%;"></div>
        </div>
        <el-table :data="monthlySales" class="analytics-table" style="width: 100%">
          <el-table-column prop="month" label="月份" />
          <el-table-column prop="total_amount" label="销售额" />
        </el-table>
        <el-pagination
            v-model:currentPage="currentPageMonthly"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="monthlySales.length"
            @current-change="handleMonthlyPageChange"
        />
      </el-tab-pane>
      <el-tab-pane label="每日考勤率" name="attendance">
        <div class="chart-container">
          <div id="attendanceChart" class="chart" style="height: 600px; width: 100%;"></div>
        </div>
        <el-table :data="dailyAttendanceRate" class="analytics-table" style="width: 100%">
          <el-table-column prop="date" label="日期" />
          <el-table-column prop="attendance_rate" label="考勤率(%)" />
        </el-table>
        <el-pagination
            v-model:currentPage="currentPageAttendance"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="dailyAttendanceRate.length"
            @current-change="handleAttendancePageChange"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import http from '@/axios/http';
import * as echarts from 'echarts';

const activeTab = ref('sales');
const dailySales = ref([]);
const monthlySales = ref([]);
const dailyAttendanceRate = ref([]);

const currentPageSales = ref(1);
const currentPageMonthly = ref(1);
const currentPageAttendance = ref(1);
const pageSize = ref(10);

const fetchDailySales = async () => {
  try {
    const response = await http.get('/glsb/daily-orders-amount');
    dailySales.value = response.data.map(item => ({
      ...item,
      date: formatDate(item.date)
    }));
    renderSalesChart();
  } catch (error) {
    console.error('获取每日销售额失败:', error);
  }
};

const fetchMonthlySales = async () => {
  try {
    const response = await http.get('/glsb/monthly-orders-amount');
    monthlySales.value = response.data.map(item => ({
      ...item,
      month: item.month
    }));
    renderMonthlySalesChart();
  } catch (error) {
    console.error('获取每月销售额失败:', error);
  }
};

const fetchDailyAttendanceRate = async () => {
  try {
    const response = await http.get('/glsb/daily-attendance-rate');
    dailyAttendanceRate.value = response.data.map(item => ({
      ...item,
      date: formatDate(item.date)
    }));
    renderAttendanceChart();
  } catch (error) {
    console.error('获取每日考勤率失败:', error);
  }
};

const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const formatMonth = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  return `${year}-${month}`;
};

const renderSalesChart = () => {
  const chart = echarts.init(document.getElementById('salesChart'));
  const xData = dailySales.value.map(item => item.date);
  const yData = dailySales.value.map(item => item.total_amount);

  const option = {
    title: {
      text: '每日销售额',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLine: {
        lineStyle: {
          color: '#666'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#666'
        }
      }
    },
    series: [
      {
        data: yData,
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: '#2196F3'
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  };

  chart.setOption(option);

  const handleResize = () => {
    chart.resize();
  };

  window.addEventListener('resize', handleResize);

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    chart.dispose();
  });
};

const renderMonthlySalesChart = () => {
  const chart = echarts.init(document.getElementById('monthlySalesChart'));
  const xData = monthlySales.value.map(item => item.month);
  const yData = monthlySales.value.map(item => item.total_amount);

  const option = {
    title: {
      text: '每月销售额',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLine: {
        lineStyle: {
          color: '#666'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#666'
        }
      }
    },
    series: [
      {
        data: yData,
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: '#2196F3'
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  };

  chart.setOption(option);

  const handleResize = () => {
    chart.resize();
  };

  window.addEventListener('resize', handleResize);

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    chart.dispose();
  });
};

const renderAttendanceChart = () => {
  const chart = echarts.init(document.getElementById('attendanceChart'));
  const xData = dailyAttendanceRate.value.map(item => item.date);
  const yData = dailyAttendanceRate.value.map(item => item.attendance_rate);

  const option = {
    title: {
      text: '每日考勤率',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLine: {
        lineStyle: {
          color: '#666'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#666'
        }
      }
    },
    series: [
      {
        data: yData,
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#FF69B4'
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  };

  chart.setOption(option);

  const handleResize = () => {
    chart.resize();
  };

  window.addEventListener('resize', handleResize);

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    chart.dispose();
  });
};

const handleSalesPageChange = (newPage) => {
  currentPageSales.value = newPage;
};

const handleMonthlyPageChange = (newPage) => {
  currentPageMonthly.value = newPage;
};

const handleAttendancePageChange = (newPage) => {
  currentPageAttendance.value = newPage;
};

onMounted(() => {
  fetchDailySales();
  fetchMonthlySales();
  fetchDailyAttendanceRate();
});
</script>

<style scoped>
.store-analytics-container {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.analytics-tabs {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.chart-container {
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.analytics-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.analytics-table th,
.analytics-table td {
  text-align: center;
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.analytics-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.analytics-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>